package com.hue.concurrent.day05;

import java.util.concurrent.locks.LockSupport;

/**
 * 使用park、unpark来实现两个线程的交替输出
 */
public class Demo07 {
    public static ParkUnPark parkUnPark = new ParkUnPark();
    public static Thread t1 = null;
    public static Thread t2 = null;
    public static Thread t3 = null;

    public static void main(String[] args){
        t1 = new Thread(() -> {
            parkUnPark.print("a", t2);
        });

        t2 = new Thread(() -> {
            parkUnPark.print("b", t3);
        });

        t3 = new Thread(() -> {
            parkUnPark.print("c", t1);
        });
        t1.start();
        t2.start();
        t3.start();
        LockSupport.unpark(t1);
    }

    public static class ParkUnPark {
        public void print(String str, Thread next) {
            while (true) {
                LockSupport.park();
                System.out.println(str);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LockSupport.unpark(next);
            }
        }
    }
}

